package com.jjwxc.jwjskandriod.readActivity;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.DisplayCutout;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.LoginActivity;
import com.jjwxc.jwjskandriod.activity.WebActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.utils.FFLogUtil;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.model.BookMarkRequest;
import com.jjwxc.jwjskandriod.model.HistoryRequest;
import com.jjwxc.jwjskandriod.model.SubscribeRequest;
import com.jjwxc.jwjskandriod.model.UserBalanceResponse;
import com.jjwxc.jwjskandriod.model.VipDistanceResponse;
import com.jjwxc.jwjskandriod.readActivity.base.BaseMVPActivity;
import com.jjwxc.jwjskandriod.readActivity.bean.BookChapterBean;
import com.jjwxc.jwjskandriod.readActivity.bean.CollBookBean;
import com.jjwxc.jwjskandriod.readActivity.dao.MyContentProvider;
import com.jjwxc.jwjskandriod.readActivity.local.BookRepository;
import com.jjwxc.jwjskandriod.readActivity.local.ReadSettingManager;
import com.jjwxc.jwjskandriod.readActivity.ui.ReadBgDialog;
import com.jjwxc.jwjskandriod.readActivity.ui.ReadTextDialog;
import com.jjwxc.jwjskandriod.readActivity.ui.WebBookModelControl;
import com.jjwxc.jwjskandriod.readActivity.utils.BrightnessUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.Constant;
import com.jjwxc.jwjskandriod.readActivity.utils.FileUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.Logger;
import com.jjwxc.jwjskandriod.readActivity.utils.RxUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.ScreenUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.StringUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.SystemBarUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.readActivity.view.PageLoader;
import com.jjwxc.jwjskandriod.readActivity.view.PageMode;
import com.jjwxc.jwjskandriod.readActivity.view.PageView;
import com.jjwxc.jwjskandriod.readActivity.view.TxtChapter;
import com.jjwxc.jwjskandriod.util.StatusBarUtil;
import com.jjwxc.jwjskandriod.widget.AutoPagePop;
import com.jjwxc.jwjskandriod.widget.BollotBombPop;
import com.jjwxc.jwjskandriod.widget.BuyMonthlyPop;
import com.jjwxc.jwjskandriod.widget.BuyWjbPop;
import com.jjwxc.jwjskandriod.widget.CategoryPop;
import com.jjwxc.jwjskandriod.widget.DownMorePop;
import com.jjwxc.jwjskandriod.widget.PopViewUtil;
import com.jjwxc.jwjskandriod.widget.ReadBuyVipPop;
import com.jjwxc.jwjskandriod.widget.ReadMorePop;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class ReadActivity extends BaseMVPActivity<ReadContract.Presenter>
        implements ReadContract.View {
    private static final String TAG = "ReadActivity";
    public static final int REQUEST_MORE_SETTING = 1;
    public static final String EXTRA_COLL_BOOK = "extra_coll_book";
    public static final String EXTRA_IS_COLLECTED = "extra_is_collected";

    // 注册 Brightness 的 uri
    private final Uri BRIGHTNESS_MODE_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
    private final Uri BRIGHTNESS_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
    private final Uri BRIGHTNESS_ADJ_URI =
            Settings.System.getUriFor("screen_auto_brightness_adj");

    private static final int WHAT_CATEGORY = 1;
    private static final int WHAT_CHAPTER = 2;
    //自动翻页
    private static final int WHAT_AUTO = 3;
    //余额
    private int mBalance;
    //余额是否充足
    private boolean mSufficientBalance = true;

    /**
     * 章的索引变化
     */
    private int mChapterPos;
    //加载目录数据集合
    List<TxtChapter> mChapterList = new ArrayList<>();
    //进入时间
    private long time;

    ConstraintLayout mAblTopMenu;

    PageView mPvPage;

    LinearLayout mLlPageTip;
    TextView mTvPageTip;
    TextView mTvPageTip2;

    LinearLayout iv_back;
    LinearLayout ll_read_vip;
    TextView tv_balance;
    TextView tv_buy;
    TextView tv_batch;
    ImageView img_more;

    LinearLayout mLlBottomMenu;
    TextView mTvPreChapter;
    SeekBar mSbChapterProgress;
    TextView mTvNextChapter;
    LinearLayout mTvCategory;
    LinearLayout mTvNightMode;
    LinearLayout ll_shuqian;
    LinearLayout mTvSetting;
    LinearLayout ll_xuzhi;
    LinearLayout ll_liwu;
    LinearLayout ll_gmxy;
    LinearLayout ll_auth;
    CheckBox cb_auth;
    ImageView img_mark;
    TextView tv_mark;

    private ReadBgDialog mReadBgDialog;
    private PageLoader mPageLoader;
    private Animation mTopInAnim;
    private Animation mTopOutAnim;
    private Animation mBottomInAnim;
    private Animation mBottomOutAnim;
    private CollBookBean mCollBook;
    //控制屏幕常亮
    private PowerManager.WakeLock mWakeLock;
    public static String mBookCode = "";
    public static boolean userIsVip = false;

    //广播的code
    //无权限有VIP
    public static String BOOK_VIP = "BOOK_VIP";
    //无权限无VIP
    public static String BOOK_NO = "BOOK_NO";
    public static String BOOK_MONTH = "BOOK_MONTH";
    //有权限
    public static String BOOK_AUTH = "BOOK_AUTH";
    //游客登录
    public static String BOOK_TOURIST = "BOOK_TOURIST";
    public static String nightMode = "nightMode";
    //自动翻页是否开启
    public static boolean autoPage = false;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case WHAT_CATEGORY:
                    mChapterPos = mPageLoader.getChapterPos();
                    break;
                case WHAT_CHAPTER:
                    mPageLoader.openChapter();
                    break;
                case WHAT_AUTO:
                    //开启翻页
                    mPageLoader.skipToNextPage();
                    break;
            }
        }
    };
    // 接收电池信息和时间更新的广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra("level", 0);
                mPageLoader.updateBattery(level);
            }
            // 监听分钟的变化
            else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mPageLoader.updateTime();
                //阅读时长心跳
                addReadingTime();
            } else if (intent.getAction().equals(nightMode)) {
                //调整暗夜模式
                toggleNightMode();
            } else if (intent.getAction().equals(BOOK_TOURIST)) {
                setReadVipInfo(BOOK_TOURIST);
            } else if (intent.getAction().equals(BOOK_VIP)) {
                setReadVipInfo(BOOK_VIP);
            } else if (intent.getAction().equals(BOOK_MONTH)) {
                setReadVipInfo(BOOK_MONTH);
            } else if (intent.getAction().equals(BOOK_NO)) {
                setReadVipInfo(BOOK_NO);
            } else if (intent.getAction().equals(BOOK_AUTH)) {
                setReadVipInfo(BOOK_AUTH);
            }
        }
    };

    // 亮度调节监听
    // 由于亮度调节没有 Broadcast 而是直接修改 ContentProvider 的。所以需要创建一个 Observer 来监听 ContentProvider 的变化情况。
    private ContentObserver mBrightObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange);

            // 判断当前是否跟随屏幕亮度，如果不是则返回
//            if (selfChange || !mSettingDialog.isBrightFollowSystem()) return;

            // 如果系统亮度改变，则修改当前 Activity 亮度
            if (BRIGHTNESS_MODE_URI.equals(uri)) {
            } else if (BRIGHTNESS_URI.equals(uri) && !BrightnessUtils.isAutoBrightness(ReadActivity.this)) {
                BrightnessUtils.setBrightness(ReadActivity.this, BrightnessUtils.getScreenBrightness(ReadActivity.this));
            } else if (BRIGHTNESS_ADJ_URI.equals(uri) && BrightnessUtils.isAutoBrightness(ReadActivity.this)) {
                BrightnessUtils.setDefaultBrightness(ReadActivity.this);
            } else {
            }
        }
    };

    private boolean isCollected = false; // isFromSDCard


    private boolean isFullScreen = false;
    private boolean isRegistered = false;
    //是不是跳转过来的，用于判断VIP自动购买
    private boolean isFormSkip = false;

    private String mBookId;


    @Override
    protected int getContentId() {
        return R.layout.activity_read;
    }

    @Override
    protected ReadContract.Presenter bindPresenter() {
        return new ReadPresenter();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mCollBook = getIntent().getParcelableExtra(EXTRA_COLL_BOOK);
        isCollected = getIntent().getBooleanExtra(EXTRA_IS_COLLECTED, false);

        isFullScreen = ReadSettingManager.getInstance().isFullScreen();

        mBookId = mCollBook.get_id();
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        //设置标题
        toolbar.setTitle(mCollBook.getTitle());
        //半透明化StatusBar
        SystemBarUtils.transparentStatusBar(this);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        ll_auth = findViewById(R.id.ll_auth);
        ll_xuzhi = findViewById(R.id.ll_xuzhi);
        ll_read_vip = findViewById(R.id.ll_read_vip);
        tv_balance = findViewById(R.id.tv_balance);
        tv_buy = findViewById(R.id.tv_buy);
        tv_batch = findViewById(R.id.tv_batch);
        ll_shuqian = findViewById(R.id.ll_shuqian);
        cb_auth = findViewById(R.id.cb_auth);
        img_mark = findViewById(R.id.img_mark);
        tv_mark = findViewById(R.id.tv_mark);


        iv_back = findViewById(R.id.iv_back);
        img_more = findViewById(R.id.img_more);
        /*************top_menu_view*******************/
        mAblTopMenu = findViewById(R.id.read_abl_top_menu);
//        mTvBrief = findViewById(R.id.read_tv_brief);
        /***************content_view******************/
        mPvPage = findViewById(R.id.read_pv_page);
        /***************bottom_menu_view***************************/
        mLlPageTip = findViewById(R.id.read_ll_page_tip);
        mTvPageTip = findViewById(R.id.read_tv_page_tip);
        mTvPageTip2 = findViewById(R.id.read_tv_page_tip_2);

        mLlBottomMenu = findViewById(R.id.read_ll_bottom_menu);
        mTvPreChapter = findViewById(R.id.read_tv_pre_chapter);
        mSbChapterProgress = findViewById(R.id.read_sb_chapter_progress);
        mTvNextChapter = findViewById(R.id.read_tv_next_chapter);
        mTvCategory = findViewById(R.id.read_tv_category);
        mTvNightMode = findViewById(R.id.read_tv_night_mode);
        mTvSetting = findViewById(R.id.read_tv_setting);
        ll_liwu = findViewById(R.id.ll_liwu);
        ll_gmxy = findViewById(R.id.ll_gmxy);

        // 如果 API < 18 取消硬件加速
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mPvPage.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        tv_balance.setText("余额" + mBalance + "船票");

        //获取页面加载器
        mPageLoader = mPvPage.getPageLoader(mCollBook);
        mReadBgDialog = new ReadBgDialog(this, mPageLoader);
        mReadBgDialog.setVipDialogShow((view ->
                new ReadBuyVipPop().readBuyVipWindow(view, ReadActivity.this, mChapterList, mChapterPos)));

        //自动加载购买5章
        cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
        // 夜间模式的状态
        toggleNightMode();
        //设置用户是不是VIP
        mPageLoader.setUserIsVip(userIsVip);
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(BOOK_NO);
        intentFilter.addAction(BOOK_VIP);
        intentFilter.addAction(BOOK_MONTH);
        intentFilter.addAction(BOOK_AUTH);
        intentFilter.addAction(BOOK_TOURIST);
        intentFilter.addAction(nightMode);
        registerReceiver(mReceiver, intentFilter);

        //设置当前Activity的Brightness
        if (ReadSettingManager.getInstance().getBrightness() == 40) {
            BrightnessUtils.setDefaultBrightness(this);
        } else {
            BrightnessUtils.setBrightness(this, ReadSettingManager.getInstance().getBrightness());
        }

        //初始化屏幕常亮类
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ireader:keep bright");

        //隐藏StatusBar
        mPvPage.post(
                () -> hideSystemBar()
        );

        //初始化TopMenu
        initTopMenu();

        //初始化BottomMenu
        initBottomMenu();
    }

    private void initTopMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            mAblTopMenu.setPadding(0, ScreenUtils.getStatusBarHeight(), 0, 0);
        }
    }

    private void initBottomMenu() {
        //判断是否全屏
        if (ReadSettingManager.getInstance().isFullScreen()) {
            //还需要设置mBottomMenu的底部高度
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
            params.bottomMargin = ScreenUtils.getNavigationBarHeight();
            mLlBottomMenu.setLayoutParams(params);
        } else {
            //设置mBottomMenu的底部距离
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
            params.bottomMargin = 0;
            mLlBottomMenu.setLayoutParams(params);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // 导航条设置透明，内容延申至全屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        }
        Log.d(TAG, "onWindowFocusChanged: " + mAblTopMenu.getMeasuredHeight());
    }

    private void toggleNightMode() {
        if (ReadSettingManager.getInstance().isNightMode()) {
            mAblTopMenu.setBackgroundResource(R.color.back_read);
            mLlBottomMenu.setBackgroundResource(R.color.back_read);

            changePageTipBG(true);
        } else {
            mAblTopMenu.setBackgroundResource(R.color.white);
            mLlBottomMenu.setBackgroundResource(R.color.white);

            changePageTipBG(false);
        }
    }

    // 注册亮度观察者
    private void registerBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (!isRegistered) {
                    final ContentResolver cr = getContentResolver();
                    cr.unregisterContentObserver(mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_ADJ_URI, false, mBrightObserver);
                    cr.registerContentObserver(MyContentProvider.CONTENT_URI, false, mBrightObserver);
                    isRegistered = true;
                }
            }
        } catch (Throwable throwable) {
            Logger.e(TAG, "register mBrightObserver error! " + throwable);
        }
    }

    //解注册
    private void unregisterBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (isRegistered) {
                    getContentResolver().unregisterContentObserver(mBrightObserver);
                    isRegistered = false;
                }
            }
        } catch (Throwable throwable) {
            Logger.e(TAG, "unregister BrightnessObserver error! " + throwable);
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        ll_read_vip.setOnClickListener(v -> {
            MobclickAgent.onEvent(ReadActivity.this, UMConstant.Event_Reader_Vip_Tip);
        });
//        ll_auth.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                PreUtils.setBoolean(mBookId, !PreUtils.getBoolean(mBookId, false));
//                cb_auth.setChecked(!PreUtils.getBoolean(mBookId, false));
//            }N
//        });
        cb_auth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PreUtils.setBoolean(mBookId, !PreUtils.getBoolean(mBookId, false));
                cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
                isFormSkip = true;
                MobclickAgent.onEvent(ReadActivity.this, UMConstant.Event_Reader_Atuo_Five);
            }
        });

        ll_gmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(ReadActivity.this, WebActivity.class);
                intent.putExtra("WEB_URL", Url.help4);
                intent.putExtra("WEB_NAME", "购买须知");
                startActivity(intent);
            }
        });

        img_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ReadMorePop().readMoreWindow(v, ReadActivity.this, mCollBook, mChapterList, mChapterPos, new ReadMorePop.ReadMoreListener() {
                    @Override
                    public void onValueClick(String value) {
                        cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
                    }
                });

                MobclickAgent.onEvent(ReadActivity.this, UMConstant.reader_ToolBar_More);
            }
        });
        ll_shuqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int markNum = PreUtils.getInt(mBookId + "_" + mPageLoader.getTxtChapter().getChapterId(), -1);
                //判断当前页面，是否和计算出来的一直，是否有权限
//                if (mPageLoader.wordToPage(markNum) != mPageLoader.getPagePos() + 1 && (StringUtils.isEmpty(mBookCode) || mBookCode.equals(BOOK_AUTH))) {
                if (markNum != mPageLoader.getPagePos() && (StringUtils.isEmpty(mBookCode) || mBookCode.equals(BOOK_AUTH))) {
                    addAddBookmark();
                    PreUtils.setInt(mBookId + "_" + mPageLoader.getTxtChapter().getChapterId(), mPageLoader.getPagePos());
                    img_mark.setImageResource(R.mipmap.mark_icon);
                    tv_mark.setTextColor(Color.parseColor("#4D998D"));

                    ll_shuqian.setClickable(false);
                } else {
                    FFApplication.showToast("请先购买，在添加书签");
                }

                MobclickAgent.onEvent(ReadActivity.this, UMConstant.reader_ToolBar_BookMark);
            }
        });
        ll_liwu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreUtils.getBoolean("tourist", false)) {
                    Intent intent = new Intent();
                    intent.setClass(ReadActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
//                    new GiftsPop(v, ReadActivity.this, mBookId, value -> PopViewUtil.sendGifePop(v, ReadActivity.this, value));

                    new BollotBombPop(v, ReadActivity.this, mBookId, new BollotBombPop.PopReturnListener() {
                        @Override
                        public void onValueClick(String value) {
                            PopViewUtil.sendGifePop(v, ReadActivity.this, value);
                        }
                    });
                }

                MobclickAgent.onEvent(ReadActivity.this, UMConstant.ReaderToolBarGift);
            }
        });
        tv_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBookCode.equals(BOOK_TOURIST)) {
                    Intent intent = new Intent();
                    intent.setClass(ReadActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    MobclickAgent.onEvent(ReadActivity.this, UMConstant.Event_Reader_Cur_Chapter_Btn);
                    //购买章节
                    TxtChapter txtChapter = mPageLoader.getTxtChapter();
                    if (null == txtChapter) {
                        return;
                    }
                    if (mBalance >= Integer.parseInt(txtChapter.getPrice())) {
                        List<String> list = new ArrayList<>();
                        list.add(txtChapter.getChapterId());
                        //购买完成，启用自动购买功能
                        isFormSkip = false;
                        //单独购买
                        buySubscribe("single", list);
                        //在自动购买5章(不包含当前章节）
                        autoSixBuySubscribe();
                    } else {
                        new BuyWjbPop().buyWjbWindow(v, ReadActivity.this, txtChapter.getPrice(),
                                value -> {
                                    //更新余额
                                    getBalance();
                                });
                    }

                }
            }
        });
        tv_batch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //批量购买
                if (mBookCode.equals(BOOK_VIP)) {
                    new DownMorePop().downMorePopWindow(v, ReadActivity.this, mChapterList,
                            mChapterPos, mCollBook.isMonthSubscribe(), new DownMorePop.DownMoreListener() {
                                @Override
                                public void onItemClick(int value) {
                                    // 刷新章节列表
                                    refreshBookCategory(true);
                                }
                            });
                } else if (mBookCode.equals(BOOK_MONTH)) {//购买包月
                    BuyMonthlyPop.bugMonthly(v, ReadActivity.this, new BuyMonthlyPop.BuyMonthPopListener() {
                        @Override
                        public void onOkClick(String group) {
                            // 刷新章节列表
                            refreshBookCategory(true);
                        }
                    });
                } else if (mBookCode.equals(BOOK_NO)) {//购买vip
                    new ReadBuyVipPop().readBuyVipWindow(v, ReadActivity.this, mChapterList, mChapterPos);
                }

            }
        });
        mPageLoader.setOnPageChangeListener(
                new PageLoader.OnPageChangeListener() {

                    @Override
                    public void onChapterChange(int pos) {
                        if (mChapterList.isEmpty()) { // 如果目录列表没有显示则不处理
                            return;
                        }
                        FFLogUtil.i("setOnPageChangeListener", "onChapterChange   pos:" + pos);
                        //判断上一章节是否是有权限
                        if (mChapterPos > pos && !mChapterList.get(pos).isHasAuth()) {
                            isFormSkip = true;
                        }
                        //赋值
                        mChapterPos = pos;
                        //判断章节是否自动购买
                        if (isFormSkip && mChapterList.get(mChapterPos).isHasAuth()) {
                            isFormSkip = false;
                        }

                        mSbChapterProgress.post(() -> {
                            mSbChapterProgress.setProgress(pos);
                        });
                    }

                    @Override
                    public void requestChapters(List<TxtChapter> requestChapters) {
                        mPresenter.loadChapter(mBookId, requestChapters);
                        mHandler.sendEmptyMessage(WHAT_CATEGORY);
                        //隐藏提示
//                        mTvPageTip.setVisibility(GONE);
                        mLlPageTip.setVisibility(GONE);
                    }

                    @Override
                    public void onCategoryFinish(List<TxtChapter> chapters) {
                        mChapterList.clear();
                        mChapterList.addAll(chapters);
                    }

                    @Override
                    public void onPageCountChange(int count) {
                        mSbChapterProgress.setMax(Math.max(0, count - 1));
//                        mSbChapterProgress.setProgress(0);
                        // 如果处于错误状态，那么就冻结使用
                        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING
                                || mPageLoader.getPageStatus() == PageLoader.STATUS_ERROR) {
                            mSbChapterProgress.setEnabled(false);
                        } else {
                            mSbChapterProgress.setEnabled(true);
                        }
                    }

                    @Override
                    public void onPageChange(int pos) {
                        FFLogUtil.i("setOnPageChangeListener", "onPageChange  pos:" + pos);
                        /*mSbChapterProgress.post(() -> {
                            mSbChapterProgress.setProgress(pos);
                        });*/
                        mPageLoader.setLoadBookAuth(true);
                        //mSbChapterProgress.post(
//                                () -> mSbChapterProgress.setProgress(pos)
//                        );


                    }
                }
        );

        mSbChapterProgress.setOnSeekBarChangeListener(
                new SeekBar.OnSeekBarChangeListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (mLlBottomMenu.getVisibility() == VISIBLE) {
                            //显示标题
//                            mTvPageTip.setText((progress + 1) + "/" + (mSbChapterProgress.getMax() + 1));
//                            mTvPageTip.setVisibility(VISIBLE);

                            if (mPageLoader == null || mPageLoader.getTxtChapter() == null) return;


                            //显示标题
                            mTvPageTip.setText(mPageLoader.getChapterCategory().get(progress).getTitle());
                            mTvPageTip2.setText((progress + 1) + "章/" + (mSbChapterProgress.getMax() + 1) + "章");
                            mLlPageTip.setVisibility(VISIBLE);
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        /*//进行切换
                        int pagePos = mSbChapterProgress.getProgress();
                        if (pagePos != mPageLoader.getPagePos()) {
                            mPageLoader.skipToPage(pagePos);
                        }
                        //隐藏提示
                        mTvPageTip.setVisibility(GONE);*/


                        //进行切换
                        int chapterPos = mSbChapterProgress.getProgress();
                        if (chapterPos != mPageLoader.getChapterPos()) {
                            mPageLoader.skipToChapter(chapterPos);
                        }
                        mLlPageTip.setVisibility(GONE);
                    }
                }
        );

        mPvPage.setTouchListener(new PageView.TouchListener() {
            @Override
            public boolean onTouch() {
                isPaused = true;
                return !hideReadMenu();
            }

            @Override
            public void center() {
                toggleMenu(true);
            }

            @Override
            public void prePage() {
            }

            @Override
            public void nextPage() {
            }

            @Override
            public void cancel() {
            }

            @Override
            public void up() {
                isPaused = false;
            }

            @Override
            public void back() {
                finish();
            }
        });


        mTvCategory.setOnClickListener(
                (v) -> {
                    new CategoryPop().categoryPopWindow(v, ReadActivity.this, mChapterList,
                            mChapterPos, mCollBook.isMonthSubscribe(), new CategoryPop.CategoryItemListener() {
                                @Override
                                public void onItemClick(int chapter, int page) {
                                    if (page != 0 && mPageLoader.mBookRecord != null) {
//                                        int mPage = mPageLoader.wordToPage(page) - 1;
                                        int mPage = page;
                                        if (mPage >= 0) {
                                            mPageLoader.mBookRecord.setChapter(chapter);
                                            mPageLoader.mBookRecord.setPagePos(mPage);
                                            mPageLoader.isChapterOpen = false;
                                        }
                                    }
                                    //跳转过来的VIP章节不自动购买
                                    if (!mChapterList.get(chapter).isHasAuth()) {
                                        isFormSkip = true;
                                    }
                                    mPageLoader.skipToChapter(chapter);
                                }
                            });
                    //切换菜单
                    toggleMenu(true);

                    MobclickAgent.onEvent(ReadActivity.this, UMConstant.reader_ToolBar_Catalog);
                }
        );
        mTvSetting.setOnClickListener(
                (v) -> {
                    toggleMenu(false);
                    new ReadTextDialog(this, mPageLoader, new ReadTextDialog.AutoPageState() {
                        @Override
                        public void onItemClick(boolean state) {
                            //默认开启翻页
                            autoPage = true;
                            new AutoPagePop().autoPopWindow(v, ReadActivity.this, mPageLoader, new AutoPagePop.AutoPageState() {
                                @Override
                                public void onItemClick(double speed, boolean isClose) {
                                    Log.e("定时器开始", "" + isClose);
                                    //开启定时器
                                    startTimerAutoPage(speed);

                                }
                            });
                        }
                    }).show();
                    MobclickAgent.onEvent(ReadActivity.this, UMConstant.Event_Reader_ToolBar_Setup);
                }
        );

        mTvPreChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipPreChapter()) {
                        mChapterPos = mPageLoader.getChapterPos();
                    }
                }
        );

        mTvNextChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipNextChapter()) {
                        mChapterPos = mPageLoader.getChapterPos();
                    }
                }
        );

        mTvNightMode.setOnClickListener(
                (v) -> {
                    toggleMenu(false);
                    mReadBgDialog.show();
                    MobclickAgent.onEvent(ReadActivity.this, UMConstant.ReaderToolBarBackground);
                }
        );
//退出阅读器
        iv_back.setOnClickListener(v -> {
            backPressd();
            MobclickAgent.onEvent(ReadActivity.this, UMConstant.reader_ToolBar_Back);
        });
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private boolean hideReadMenu() {
        //如果是自动播放的话弹窗
        if (autoPage) {
            return false;
        }
        hideSystemBar();
        if (mAblTopMenu.getVisibility() == VISIBLE) {
            toggleMenu(true);
            return true;
        }
//        else if (mSettingDialog.isShowing()) {
//            mSettingDialog.dismiss();
//            return true;
//        }
        MobclickAgent.onEvent(ReadActivity.this, UMConstant.Page_Reader_ToolBar);
        return false;
    }

    private void showSystemBar() {
        //显示
        SystemBarUtils.showUnStableStatusBar(this);
        if (isFullScreen) {
            SystemBarUtils.showUnStableNavBar(this);
        }
    }

    private void hideSystemBar() {
        //隐藏
        SystemBarUtils.hideStableStatusBar(this);
        if (isFullScreen) {
            SystemBarUtils.hideStableNavBar(this);
        }
    }

    /**
     * 切换菜单栏的可视状态
     * 默认是隐藏的
     */
    private void toggleMenu(boolean hideStatusBar) {
//        if (null == mPageLoader.getTxtChapter()) {
//            return;
//        }
        if (autoPage) {
            stopTimerAutoPage();
            new AutoPagePop().autoPopWindow(mPvPage, ReadActivity.this, mPageLoader, new AutoPagePop.AutoPageState() {

                @Override
                public void onItemClick(double speed, boolean isClose) {
                    //开启定时器
                    startTimerAutoPage(speed);
                    if (isClose) {//关闭自动翻页
                        autoPage = false;
                        //关闭定时器
                        stopTimerAutoPage();
                    }
                }
            });
            return;
        }

        initMenuAnim();

        if (mAblTopMenu.getVisibility() == VISIBLE) {
            //关闭
            mAblTopMenu.startAnimation(mTopOutAnim);
            mLlBottomMenu.startAnimation(mBottomOutAnim);
            mAblTopMenu.setVisibility(GONE);
            mLlBottomMenu.setVisibility(GONE);
//            mTvPageTip.setVisibility(GONE);
            mLlPageTip.setVisibility(GONE);

            if (hideStatusBar) {
                hideSystemBar();
            }
        } else {
            mAblTopMenu.setVisibility(VISIBLE);
            mLlBottomMenu.setVisibility(VISIBLE);
            mAblTopMenu.startAnimation(mTopInAnim);
            mLlBottomMenu.startAnimation(mBottomInAnim);

            showSystemBar();

            if (null != mPageLoader.getTxtChapter()) {
                int markNum = PreUtils.getInt(mBookId + "_" + mPageLoader.getTxtChapter().getChapterId(), -1);
                //            if (markNum >= 0 && mPageLoader.wordToPage(markNum) == mPageLoader.getPagePos() + 1) {
                if (markNum >= 0 && markNum == mPageLoader.getPagePos()) {
                    img_mark.setImageResource(R.mipmap.mark_icon);
                    tv_mark.setTextColor(Color.parseColor("#4D998D"));
                    ll_shuqian.setClickable(false);
                } else {
                    img_mark.setImageResource(R.mipmap.shuqian);
                    tv_mark.setTextColor(Color.parseColor("#4E4E4E"));
                    ll_shuqian.setClickable(true);
                }
            }
        }

        MobclickAgent.onEvent(this, UMConstant.Page_Reader_ToolBar);
    }

    //初始化菜单动画
    private void initMenuAnim() {
        if (mTopInAnim != null) return;

        mTopInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_in);
        mTopOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_out);
        mBottomInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_in);
        mBottomOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_out);
        //退出的速度要快
        mTopOutAnim.setDuration(200);
        mBottomOutAnim.setDuration(200);
    }


    @Override
    protected void processLogic() {
        super.processLogic();
        try {
            // 如果是已經收藏的，那麼就從數據庫中獲取目錄
            /*if (isCollected) {
                Disposable disposable = BookRepository.getInstance()
                        .getBookChaptersInRx(mBookId)
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(
                                (bookChapterBeen, throwable) -> {
                                    // 設置 CollBook
                                    mPageLoader.getCollBook().setBookChapters(bookChapterBeen);
                                    // 刷新章節列表
                                    mPageLoader.refreshChapterList(false);
                                    // 如果是網絡小說並被標記更新的，則從網絡下載目錄
                                    if (mCollBook.isUpdate() && !mCollBook.isLocal()) {
                                        mPresenter.loadCategory(mCollBook);
                                    }
                                }
                        );
                addDisposable(disposable);
            } else {*/
                // 從網絡中獲取目錄
                mPresenter.loadCategory(mCollBook);
//            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "图书解析错误,请联系管理员", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // 刪除緩存的空章節(防止加载空白数据)
        for (int i = 0; i < mCollBook.getBookChapterList().size(); i++) {
            FileUtils.chapterCachedDelete(mBookId, mCollBook.getBookChapterList().get(i).getId());
        }
        // 刷新章节列表
        refreshBookCategory(true);
    }

    @Override
    public void showCategory(List<BookChapterBean> bookChapters) {
        mPageLoader.getCollBook().setBookChapters(bookChapters);
        mPageLoader.refreshChapterList(false);

        // 如果是目录更新的情况，那么就需要存储更新数据
        if (mCollBook.isUpdate() && isCollected) {
            BookRepository.getInstance()
                    .saveBookChaptersWithAsync(bookChapters);
        }
    }

    @Override
    public void finishChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mHandler.sendEmptyMessage(WHAT_CHAPTER);
        }

    }

    @Override
    public void errorChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mPageLoader.chapterError();
        }
    }

    @Override
    public void onBackPressed() {
        if (mAblTopMenu.getVisibility() == VISIBLE) {
            // 非全屏下才收缩，全屏下直接退出
            if (!ReadSettingManager.getInstance().isFullScreen()) {
                toggleMenu(true);
                return;
            }
        }
        backPressd();
    }

    //返回的时候保存记录
    public void backPressd() {
        if (!isCollected
                && mCollBook.getBookChapters() != null && !mCollBook.getBookChapters().isEmpty()) {
            //设置阅读时间
            mCollBook.setLastRead(StringUtils.
                    dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));
            BookRepository.getInstance()
                    .saveCollBookWithAsync(mCollBook);
            exit();
        } else {
            exit();
        }
    }

    // 退出
    private void exit() {
        // 退出
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerBrightObserver();
    }

    @Override
    protected void onResume() {
        super.onResume();

        getBalance();

        mWakeLock.acquire();
        if (autoPage) {
            setAutoSpeed();
        }

        MobclickAgent.onEvent(this, UMConstant.Page_Reader);
    }

    /**
     * 设置初入此页面上次保存的速度
     */
    private void setAutoSpeed() {
        double period;
        int barNum = PreUtils.getInt(Constant.Progress, 0);
        boolean pageMode;

        //默认翻页方式  根据存储来判断
        String mode = PreUtils.getString(Constant.PageMode, PageMode.SIMULATION.name());
        if (PageMode.SIMULATION.name().equals(mode)) {
            pageMode = true;
        } else {
            pageMode = false;
        }

        if (pageMode) {
            //进度条为100,
            period = 20D - ((barNum * 15D) / 100);
            if (period <= 0) {
                period = 20L;
            }
        } else {
            /*if (barNum > 95) {
                barNum = 95;
            }

            period = 2D - (barNum * 1.8D) / 100D;
            if (period <= 0) {
                period = 0.2D;
            }*/
            period = 0.001;
        }

        startTimerAutoPage(period);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWakeLock.release();
        stopTimerAutoPage();
        if (isCollected) {
            mPageLoader.saveRecord();
            long readTime = (System.currentTimeMillis() - time) / (1000 * 60);

            // 如果这些数据为空，则不提交阅读记录
            if (TextUtils.isEmpty(mBookId) ||
                    mPageLoader.getTxtChapter() == null ||
                    TextUtils.isEmpty(mPageLoader.getTxtChapter().getChapterId()) ||
                    mChapterList.isEmpty()
            ) {
                return;
            }

            //阅读记录
            HistoryRequest historyRequest = new HistoryRequest();
            historyRequest.setBookId(mBookId);
            historyRequest.setChapterId(mPageLoader.getTxtChapter().getChapterId());
            historyRequest.setPercent(((mChapterPos + 1) / mChapterList.size()) * 100 + "%");
            historyRequest.setContentIndex(mPageLoader.getWordNum());
            historyRequest.setTodayReadingMin((int) readTime);
            addReadingHistory(historyRequest);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterBrightObserver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        stopTimerAutoPage();
        mHandler.removeMessages(WHAT_CATEGORY);
        mHandler.removeMessages(WHAT_CHAPTER);
        mHandler.removeMessages(WHAT_AUTO);

        mPageLoader.closeBook();
        mPageLoader = null;

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean isVolumeTurnPage = ReadSettingManager
                .getInstance().isVolumeTurnPage();
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (isVolumeTurnPage) {
                    return mPageLoader.skipToPrePage();
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (isVolumeTurnPage) {
                    return mPageLoader.skipToNextPage();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SystemBarUtils.hideStableStatusBar(this);
        if (requestCode == REQUEST_MORE_SETTING) {
            boolean fullScreen = ReadSettingManager.getInstance().isFullScreen();
            if (isFullScreen != fullScreen) {
                isFullScreen = fullScreen;
                // 刷新BottomMenu
                initBottomMenu();
            }

            // 设置显示状态
            if (isFullScreen) {
                SystemBarUtils.hideStableNavBar(this);
            } else {
                SystemBarUtils.showStableNavBar(this);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.fullScreenTransparent(this, true);
        if (Build.VERSION.SDK_INT >= 28) {
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(params);

            mPvPage.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets windowInsets) {
                    DisplayCutout displayCutout = windowInsets.getDisplayCutout();
                    if (displayCutout != null) {
                        int top = displayCutout.getSafeInsetTop();
                        mPageLoader.mSafeInsetTop = top;
                        mPvPage.invalidate();
                    }

                    return windowInsets.consumeSystemWindowInsets();
                }
            });
        }
        //记录进入时间
        time = System.currentTimeMillis();

        MobclickAgent.onEvent(ReadActivity.this, UMConstant.Page_Reader);
    }

    public void getBalance() {
        new FFNetWork().post(Url.balance, null, new FFNetWorkCallBack<UserBalanceResponse>() {
            @Override
            public void onSuccess(UserBalanceResponse response) {
                if (response.getCode() == 200) {
                    mBalance = response.getData().getBalance();
                    tv_balance.setText("余额" + mBalance + "船票");
                    getVipDistance();
                }

            }

            @Override
            public boolean onFail(UserBalanceResponse response) {
                return false;
            }
        }, UserBalanceResponse.class);
    }

    public void getVipDistance() {
        MobclickAgent.onEvent(ReadActivity.this, UMConstant.Event_Reader_Vip_Tip);
        new FFNetWork().post(Url.vipDistance, null, new FFNetWorkCallBack<VipDistanceResponse>() {
            @Override
            public void onSuccess(VipDistanceResponse response) {
                if (response.getCode() == 200) {
                    mReadBgDialog.setIsVip(response.getData() <= 0);
                    userIsVip = response.getData() <= 0;
                    mPageLoader.setUserIsVip(userIsVip);

                    sendsBroadcast();
                }
            }

            @Override
            public boolean onFail(VipDistanceResponse response) {
                return false;
            }
        }, VipDistanceResponse.class);
    }

    //自动购买下五章(不包含当前章节)
    public void autoSixBuySubscribe() {
        Log.e("---------------------", "isFormSkip" + isFormSkip + "---" + PreUtils.getBoolean(mBookId, false));
        if (!isFormSkip && PreUtils.getBoolean(mBookId, false)) {
            List<String> list = new ArrayList<>();
            int price = 0;
            if (mChapterPos + 6 < mChapterList.size()) {
                for (int i = mChapterPos + 1; i < mChapterPos + 6; i++) {
                    list.add(mChapterList.get(i).getChapterId());
                    price = price + Integer.parseInt(mChapterList.get(i).getPrice());
                }
            } else {
                for (int i = mChapterPos + 1; i < mChapterList.size(); i++) {
                    list.add(mChapterList.get(i).getChapterId());
                    price = price + Integer.parseInt(mChapterList.get(i).getPrice());
                }
            }
            //余额是不是够
            if (mBalance >= price) {
                mSufficientBalance = true;
                //自动购买
                buySubscribe("auto", list);
            } else {
                mSufficientBalance = false;
                refreshBookCategory(true);
            }
        }
        //如果不是目录进来的，设置为不跳过
        isFormSkip = false;
    }

    //自动购买下五章(包含当前章节)
    public void autoBuySubscribe() {
        if (!isFormSkip && PreUtils.getBoolean(mBookId, false)) {
            List<String> list = new ArrayList<>();
            int price = 0;
            if (mChapterPos + 5 < mChapterList.size()) {
                for (int i = mChapterPos; i < mChapterPos + 5; i++) {
                    list.add(mChapterList.get(i).getChapterId());
                    price = price + Integer.parseInt(mChapterList.get(i).getPrice());
                }
            } else {
                for (int i = mChapterPos; i < mChapterList.size(); i++) {
                    list.add(mChapterList.get(i).getChapterId());
                    price = price + Integer.parseInt(mChapterList.get(i).getPrice());
                }
            }
            //余额是不是够
            if (mBalance >= price) {
                mSufficientBalance = true;
                //自动购买
                buySubscribe("auto", list);
            } else {
                //余额不足
                mSufficientBalance = false;
                refreshBookCategory(true);
            }
            //如果不是目录进来的，设置为不跳过
            isFormSkip = false;
        }
    }

    public void buySubscribe(String subscribeType, List<String> ids) {
        SubscribeRequest request = new SubscribeRequest();
        request.setBookId(mBookId);
        request.setSubscribeType(subscribeType);
        request.setChapterIds(ids);
        new FFNetWork().post(Url.subscribe, null, new FFNetWorkCallBack<String>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String response) {
                if (response.contains("200")) {
                    for (String id : ids) {
                        //删除未购买已经缓存的空章节
                        FileUtils.chapterCachedDelete(mBookId, id);
                    }

                    //更新余额
                    getBalance();
                    //购买成功刷新
                    //目录和章节
                    // 刷新章节列表
                    refreshBookCategory(true);

                }

            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class, JSON.toJSONString(request));
    }

    //阅读历史上报
    public void addReadingHistory(HistoryRequest historyRequest) {
        new FFNetWork().post(Url.addReadingHistory, null, new FFNetWorkCallBack<String>() {
            @Override
            public void onSuccess(String response) {

            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class, JSON.toJSONString(historyRequest));
    }

    //阅读时长上报
    public void addReadingTime() {
        new FFNetWork().post(Url.addReadingTime, null, new FFNetWorkCallBack<String>() {
            @Override
            public void onSuccess(String response) {

            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class);
    }

    //添加书签
    public void addAddBookmark() {
        BookMarkRequest bookMarkRequest = new BookMarkRequest();
        bookMarkRequest.setBookId(mBookId);
        bookMarkRequest.setChapterName(mCollBook.getTitle());
        bookMarkRequest.setContent(mPageLoader.getPageContent().replaceAll("\\s", ""));
        bookMarkRequest.setChapterId(mPageLoader.getTxtChapter().getChapterId());
        bookMarkRequest.setLocation(mPageLoader.getPagePos() + "");
        new FFNetWork().post(Url.addBookmark, null, new FFNetWorkCallBack<String>() {
            @Override
            public void onSuccess(String response) {
                if (response.contains("200")) {
                    FFApplication.showToast("添加书签成功");
                }
            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class, JSON.toJSONString(bookMarkRequest));
    }

    /**
     * 刷新目录章节，重新缓存，重新加载
     */
    @SuppressLint("CheckResult")
    public void refreshBookCategory(boolean openChapter) {
        WebBookModelControl.getInstance()
                .getBookChapters(mCollBook)
                .doOnSuccess(new Consumer<List<BookChapterBean>>() {
                    @Override
                    public void accept(List<BookChapterBean> bookChapterBeen) throws Exception {
                        //进行设定BookChapter所属的书的id。
                        for (BookChapterBean bookChapter : bookChapterBeen) {
                            bookChapter.setId(bookChapter.getId());
                            bookChapter.setBookId(mCollBook.get_id());
                        }
                    }
                })
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        beans -> {
                            mPageLoader.getCollBook().setBookChapters(beans);
                            mPageLoader.refreshChapterList(openChapter);

                            // 如果是目录更新的情况，那么就需要存储更新数据
                            if (mCollBook.isUpdate() && isCollected) {
                                BookRepository.getInstance()
                                        .saveBookChaptersWithAsync(beans);
                            }
                        }

                );
    }

    //实现自动翻页相关
    Timer timer;
    TimerTask task;
    private boolean isPaused = false;

    /**
     * 开起定时器
     */
    private void startTimerAutoPage(double period) {
        setAutoScrollSpeed();
        if (timer == null || task == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    if (!isPaused) {
                        //自动翻页
                        mHandler.sendEmptyMessage(WHAT_AUTO);
                    }
                }
            };
            // 自动翻页定时器
            // 设置 delay 延迟时间，避免直接跳过当前页
            timer.schedule(task, (long) (period * 1000), (long) (period * 1000));
        }

    }

    private void setAutoScrollSpeed() {
        int barNum = PreUtils.getInt(Constant.Progress, -1);
        if (barNum == -1) return;

        float speed = barNum / 10F;
        if (speed <= 1) {
            speed = 1;
        }
        if (speed >= 10) {
            speed = 10;
        }

        mPvPage.setAutoScrollSpeed(speed);
    }

    /**
     * 关闭清空定时器
     */
    private void stopTimerAutoPage() {
        Log.e("定时器关闭", "");

        if (timer != null || task != null) {
            timer.cancel();
            timer = null;
            task = null;
        }
    }

    public void sendsBroadcast() {
        if (mChapterList == null || mChapterList.isEmpty()) return;

        Intent intent = new Intent();

        TxtChapter txtChapter = mChapterList.get(mChapterPos);

        if (!txtChapter.isHasAuth() && PreUtils.getBoolean("tourist", false)) {
            intent.setAction(ReadActivity.BOOK_TOURIST);
            sendBroadcast(intent);
        } else if (!txtChapter.isHasAuth() && txtChapter.isVip() && userIsVip && !txtChapter.isMonthSubscribe()) { //书是vip用户是vip 其他不是
            intent.setAction(ReadActivity.BOOK_VIP);
            sendBroadcast(intent);
            // 以下情况禁止翻页
//            mStatus = STATUS_EMPTY;
        } else if (!txtChapter.isHasAuth() && !txtChapter.isVip() && txtChapter.isMonthSubscribe()) {//包月 其他不是
            intent.setAction(ReadActivity.BOOK_MONTH);
            sendBroadcast(intent);
            // 以下情况禁止翻页
//            mStatus = STATUS_EMPTY;
        } else if (!txtChapter.isHasAuth() && txtChapter.isVip() && !userIsVip && !txtChapter.isMonthSubscribe()) {//用户不是vip,书是vip
            intent.setAction(ReadActivity.BOOK_NO);
            sendBroadcast(intent);
            // 以下情况禁止翻页
//            mStatus = STATUS_EMPTY;
        } else {
//            mStatus = STATUS_FINISH;
            intent.setAction(ReadActivity.BOOK_AUTH);
            sendBroadcast(intent);
        }
    }

    /**
     * 改变章节变更提示信息背景及字体颜色
     *
     * @param isTrue 是否更改 (夜间模式更改)
     */
    private void changePageTipBG(boolean isTrue) {
        if (isTrue) {
            mLlPageTip.setBackgroundResource(R.drawable.shape_transparent85_white_radius_10);
            mTvPageTip.setTextColor(Color.parseColor("#222222"));
            mTvPageTip2.setTextColor(Color.parseColor("#222222"));
        } else {
            mLlPageTip.setBackgroundResource(R.drawable.shape_transparent85_black_radius_10);
            mTvPageTip.setTextColor(Color.parseColor("#FFFFFF"));
            mTvPageTip2.setTextColor(Color.parseColor("#FFFFFF"));
        }
    }

    /**
     * 设置阅读VIP信息
     *
     * @param type
     */
    private void setReadVipInfo(String type) {
        ll_read_vip.setVisibility(VISIBLE);
        tv_buy.setVisibility(VISIBLE);
        cb_auth.setVisibility(VISIBLE);
        tv_batch.setVisibility(VISIBLE);
        tv_balance.setVisibility(VISIBLE);
        ll_xuzhi.setVisibility(VISIBLE);

        if (type.equals(BOOK_VIP)) {       // VIP
            mBookCode = BOOK_VIP;
            if (mSufficientBalance && !isFormSkip && PreUtils.getBoolean(mBookId, false)) {
                //是否符合自动购买
                autoBuySubscribe();
            } else {
                tv_buy.setText("购买本章（VIP专享五折" + mPageLoader.getTxtChapter().getPrice() + "船票）");
                tv_buy.setBackgroundResource(R.drawable.button_law_true);
                //自动购买选则
                cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
                tv_batch.setText("批量购买");
                tv_batch.setTextColor(Color.parseColor("#4D998D"));
                tv_batch.setBackgroundResource(R.drawable.button_law_false);
            }
        } else if (type.equals(BOOK_NO)) {       //无权限无VIP
            mBookCode = BOOK_NO;
            if (mSufficientBalance && !isFormSkip && PreUtils.getBoolean(mBookId, false)) {
                //是否符合自动购买
                autoBuySubscribe();
            } else {
                tv_buy.setText("购买本章（" + mPageLoader.getTxtChapter().getPrice() + "船票）");
                tv_buy.setBackgroundResource(R.drawable.button_law_true);
                //自动购买选则
                cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
                tv_batch.setText("成为VIP五折购书");
                tv_batch.setTextColor(Color.parseColor("#412511"));
                tv_batch.setBackgroundResource(R.mipmap.button_vip_goumai);
            }
        } else if (type.equals(BOOK_MONTH)) {    // 月卡
            mBookCode = BOOK_MONTH;
            if (mSufficientBalance && !isFormSkip && PreUtils.getBoolean(mBookId, false)) {
                //是否符合自动购买
                autoBuySubscribe();
            } else {
                tv_buy.setText("购买本章（VIP专享五折" + mPageLoader.getTxtChapter().getPrice() + "船票）");
                tv_buy.setBackgroundResource(R.drawable.button_law_true);
                //自动购买选则
                cb_auth.setChecked(PreUtils.getBoolean(mBookId, false));
                tv_batch.setText("购买包月书库本章免费看");
                tv_batch.setTextColor(Color.parseColor("#4D998D"));
                tv_batch.setBackgroundResource(R.drawable.button_law_false);
            }
        } else if (type.equals(BOOK_AUTH)) {     //有权限
            mBookCode = BOOK_AUTH;
            ll_read_vip.setVisibility(GONE);
        } else if (type.equals(BOOK_TOURIST)) {  //  游客登陆
            mBookCode = BOOK_TOURIST;
            ll_read_vip.setVisibility(VISIBLE);
            tv_batch.setVisibility(GONE);
            tv_balance.setVisibility(View.INVISIBLE);
            ll_xuzhi.setVisibility(View.INVISIBLE);
            cb_auth.setVisibility(View.INVISIBLE);

            tv_buy.setText("登录阅读书籍");
            tv_buy.setBackgroundResource(R.drawable.button_law_true);
        } else {
//            throw new IllegalStateException("Unexpected value: " + type);
            ll_read_vip.setVisibility(GONE);
        }
    }
}